package com.fgl;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.mongodb.gridfs.GridFSInputFile;
import jdk.nashorn.internal.objects.annotations.Where;
import org.bson.types.ObjectId;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * @Description
 * @Author fuguangli businessfgl@163.com
 * @Create date:    2017/9/14
 */
public class SpringDataMongoApp {

    public static void main(String[] args) throws IOException {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring-data-mongo.xml");

        MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

        Employee employee = new Employee("100", "firstName", "lastName", 23);

        // save
        mongoOperation.save(employee, "employees");

        // find
        Employee savedEmployee = mongoOperation.findOne(new Query(Criteria.where(
                "id").is("100")), Employee.class, "employees");

        System.out.println("Saved Employee: " + savedEmployee);

        // update
        mongoOperation.updateFirst(new Query(Criteria.where(
                "firstname").is("firstName")), Update.update("lastname",
                "new lastName"), "employees");

        // find
        Employee updatedEmployee = mongoOperation.findOne(new Query(
                Criteria.where("id").is("100")), Employee.class, "employees");

        System.out.println("Updated Employee: " + updatedEmployee);

        // delete
//        mongoOperation.remove(new Query(Criteria.where("id").is(
//                "100")), Employee.class,"employees");

        // List
        DBCollection listEmployee = mongoOperation.getCollection("employees");
        DBCursor cursor = listEmployee.find();
        Iterator<DBObject> iterator = cursor.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
//        System.out.println("size of employees = " + listEmployee.size());



        /*save file*/
        MongoTemplate template = (MongoTemplate) mongoOperation;
        DB db = template.getDb();
        GridFS fs = new GridFS(db, "file");
        File file = new File("D:\\Program Files (x86)\\JetBrains\\IDEA WORKSPACE-DEMO\\mongo-demo\\file\\sql_t.jpg");
        GridFSInputFile inputFile = fs.createFile(file);
        inputFile.put("contentType", file.getName().substring(file.getName().indexOf(".") + 1));
        inputFile.save();


        /*get file*/
        GridFSDBFile gridFSFile = fs.findOne("sql_t.jpg");
        InputStream inputStream = gridFSFile.getInputStream();
        File outDir = new File("D:\\Program Files (x86)\\JetBrains\\IDEA WORKSPACE-DEMO\\mongo-demo\\file\\out");
        if (!outDir.exists()) {
            outDir.mkdirs();
        }
        File outFile = new File("D:\\Program Files (x86)\\JetBrains\\IDEA WORKSPACE-DEMO\\mongo-demo\\file\\out\\out.jpg");
        if (!outFile.exists()) {
            outFile.createNewFile();
        }

        gridFSFile.writeTo(outFile);


    }


   /* or和and联合查询

    比如查询 （A = 1 and b = 2 ）or （A = 3 and b =4），or的数量不确定，

    那么采用定义一个Criteria数组，将条件组记入数组中，然后将数组指定给orCriteria方法。

    orOperator({List andOperator})
    */

//    public List<Object> find(List<Object> groupattentions) {
//　　Query query = new Query();
//　　Criteria criteria = new Criteria();
//　　Criteria[] criterialist = new Criteria[groupattentions.size()];
//　　for (int i = 0; i < groupattentions.size(); i++) {
//　　　　Criteria criteriaand = new Criteria();
//　　　　
//            criteriaand.andOperator(Criteria.where("bloggroup.$id").is(new ObjectId(groupattentions.get(i).getGroupid())).and("bloglevel").gte(groupattentions.get(i).getGrouplevel()));
//　　　　criterialist[i] = criteriaand;
//　　}
//　　criteria.orOperator(criterialist);
//　　query.addCriteria(criteria);
//　　return mongoTemplateDataBase.find(query, Blog.class);
//    }
}
